from django.db import IntegrityError
from django.db.models import Count
from django.http import JsonResponse
from db_man_app.models import Course, Score
import json

def get_all(request):
    # 获取所有课程及其选课人数
    courses = Course.objects.all()

    tableData = []
    for course in courses:
        # 使用filter来计算选修该课程的学生数
        student_count = Score.objects.filter(course=course).values('student').distinct().count()
        tableData.append({
            'course_id': course.course_id,
            'course_name': course.course_name,
            'course_number': student_count,
            'course_code': course.course_code
        })

    return JsonResponse({
        'tableData': tableData,
        'status': 'success',
        'message': '课程数据获取成功'
    })


def add_one(request):
    data = json.loads(request.body)
    course_code=data['course_code']
    course_name=data['course_name']
    try:
        Course.objects.create(course_code=course_code,course_name=course_name)
        return JsonResponse(1, safe=False)
    except IntegrityError:
        return JsonResponse(0, safe=False)

def updata_one(request):
    data = json.loads(request.body)
    course_code=data['formData']['course_code']
    course_name=data['formData']['course_name']
    old_name=data['old_name']
    try:
        Course.objects.filter(course_name=old_name).update(course_name=course_name,course_code=course_code)
        return JsonResponse(1, safe=False)
    except IntegrityError:
        return JsonResponse(0, safe=False)

def del_one(request):
    data = json.loads(request.body)
    del_name=data['del_id']
    try:
        Course.objects.filter(course_name=del_name).delete()
        return JsonResponse(1, safe=False)
    except IntegrityError:
        return JsonResponse(0, safe=False)